<template>
  <el-dialog v-model="visible" :title="`导入${leadingInInfo?.title}`" :width="480" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <div style="margin-bottom: 20px">选择上传的Excel文件</div>
    <el-upload style="width: 100%;" ref="uploadRef" drag :limit="1" :on-exceed="handleExceed" :on-change="handleChange"
      :auto-upload="false">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将文件拖放到此处或 <em>单击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          <span>注：导入前，确保必填信息填写正确。</span>
          <a :href="templateUrl" target="_blank" rel="noopener noreferrer"
            :download="`${leadingInInfo?.title}导入模板.xlsx`">点击下载Excel模板</a>
        </div>
      </template>
    </el-upload>

    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import app from '@/constants/app';
import { getToken } from '@/utils/cache';
import axios from 'axios';
import { ElMessage, ElMessageBox, UploadInstance } from "element-plus";
import { reactive, ref } from 'vue';

const leadingInInfo = ref<any>();
const templateUrl = ref();
const loading = ref(false);
const visible = ref(false);

const dataForm = reactive({
  file: '',
});

const emit = defineEmits(["refreshDataList"]);

const init = (info?: any) => {
  leadingInInfo.value = info;
  visible.value = true;

  templateUrl.value = getDownloadUrl(info.templatePath);
};

const getDownloadUrl = (templatePath: string) => {
  return `${app.api}${templatePath}?token=${getToken()}`;
};

const handleChange = (file: { name: string; raw: any; }) => {
  const fileName = file.name
  const fileType = fileName.substring(fileName.lastIndexOf('.') + 1)
  if (fileType === 'xlsx') {
    dataForm.file = file.raw
  } else {
    ElMessage.error({
      message: "上传文件只能是xlsx格式",
      duration: 500,
    });
  }
};

const handleExceed = () => {
  ElMessage.error({
    message: "超出最大上传文件数量的限制",
    duration: 500,
  });
  return
};

const uploadRef = ref<UploadInstance>()

// 表单提交
const dataFormSubmitHandle = () => {
  if (!dataForm.file) {
    ElMessage.error({
      message: "请先选择需要导入的xlsx文件",
      duration: 500,
    });
    return;
  }
  const formData = new FormData();
  formData.append('file', dataForm.file);
  loading.value = true;

  axios({
    url: app.api + leadingInInfo.value.uploadPath,
    data: formData,
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data',
      token: getToken(),
    },
  })
    .then(({ data }) => {
      if (!data?.data?.successFlag) {
        showError(data?.data?.errorFileUrl);
        ElMessage.error({
          message: "导入失败",
          duration: 500,
        });
        return;

      }
      ElMessage.success({
        message: "导入成功",
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    })
};

const showError = (errorFileUrl?: string) => {
  if (!errorFileUrl) return;
  ElMessageBox.confirm(
    '点击[确定]下载导入失败日志',
    '导入失败',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
      const link = document.createElement('a');
      link.href = errorFileUrl;
      link.setAttribute('download', '导入失败日志.xlsx');
      document.body.appendChild(link);
      link.click();
    })
}

defineExpose({
  init
});
</script>
